<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      border: 1px salmon solid;
    }
  </style>
</head>

<body>
  <!-- 画布要这样给宽高才行 -->
  <canvas width="500" height="500"></canvas>

  <script>
    // 单张图片
    // 预加载 ：等待资源加载完毕之后再使用 
    // function loadImg () {
    //   return new Promise((resolve, reject) => {
    //     let img = document.createElement("img");
    //     img.src = "./img/1.jpg";
    //     // img加载成功
    //     img.onload = function () {
    //       resolve(this)
    //     }
    //     // img加载失败
    //     img.onerror = function () {
    //       reject("图片加载失败");
    //     }
    //   })
    // }
    // loadImg().then(img=>{
    //   // 渲染图片
    //   context.drawImage(img, 0, 0, 200, 100);
    // }).catch(err=>{
    //   console.log('error', err);
    // })


    // 多张图片

    let obj = {
      bg1: './img/6.jpg',
      bg2: './img/5.jpg',
      bg3: './img/1.jpg'
    }


    function loadImg (obj, cb) {
      return new Promise(resolve => {
        let length = 0
        for (let key in obj) {
          length++;
        }
        console.log(length);
        let count = 0
        // 循环加载对象里的图片
        let resObj = {};  // 一一的对应关系
        for (let k in obj) {
          let imgEle = new Image();
          imgEle.src = obj[k]
          imgEle.onload = function () {
            count++;
            resObj[k] = this
            if (count >= length) {
              cb && cb(resObj)
              resolve(resObj)
            }
          }
        }
      })
    }

    // 获取上下文和画笔
    let canvas = document.querySelector("canvas");
    let context = canvas.getContext("2d");

    loadImg(obj).then(resObj => {
      console.log(resObj);
      context.drawImage(resObj['bg1'], 0, 0, 100, 100);
      context.drawImage(resObj['bg2'], 200, 200, 100, 100);
      context.drawImage(resObj['bg3'], 300, 300, 100, 100);
    })

  </script>
</body>

</html>